package com.ruitu.mall_98_2.mvp.presenter;

import com.beanu.arad.utils.ToastUtils;
import com.ruitu.mall_98_2.mvp.contract.AccountSettingContract;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class AccountSettingPresenter extends AccountSettingContract.Presenter {
    @Override
    public MultipartBody updateUserHead(String id, File file) {
        MediaType FORM_CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.addPart(MultipartBody.Part.createFormData("userId", null, RequestBody.create(FORM_CONTENT_TYPE, id)));
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        builder.addFormDataPart("headFile", file.getName(), requestBody);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

    @Override
    public void updateUserHead(MultipartBody multipartBody) {
        mModel.updateUserHead(multipartBody).subscribe(new SubscriberImpl<BaseResult>() {
            @Override
            public void onError(Throwable e) {
                mView.hideProgress();
                ToastUtils.showShort("修改头像失败");
            }

            @Override
            public void onNext(BaseResult baseResult) {
                mView.hideProgress();
                if (baseResult.isSuccess()) {
                    mView.setHeadImage();
                    ToastUtils.showShort(baseResult.getMsg());
                } else {
                    ToastUtils.showShort(baseResult.getMsg());
                }
            }
        });
    }

    @Override
    public void updateUserInfo(String id, String nickName, String sex) {
        mModel.updateUserInfo(id, nickName, sex)
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        mView.hideProgress();
                        e.printStackTrace();
                        ToastUtils.showShort("修改信息失败");
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        mView.hideProgress();
                        if (baseResult.isSuccess()) {
                            mView.setUserSuc();
                            ToastUtils.showShort(baseResult.getMsg());
                        } else {
                            ToastUtils.showShort(baseResult.getMsg());
                        }
                    }
                });
    }
}
